from rest_framework.response import Response
from rest_framework.views import APIView

from .models import ProductModel
from .serializers import ProductSerializer
from icdemoapi.utils.paging import LargeResultsSetPagination


class ProductView(APIView):
    """Product view"""

    def get(self, request):
        """获取数据"""
        products = ProductModel.objects.all()
        serializer = ProductSerializer(instance=products, many=True)
        return Response(serializer.data)

    def post(self, request):
        """添加数据"""
        serializer = ProductSerializer(data=request.data)

        if not serializer.is_valid():
            return Response(serializer.errors)
        else:
            serializer.save()
            return Response(serializer.data, status=201)


class ProductDetailView(APIView):
    """带主键url"""

    def get(self, request, id):
        product = ProductModel.objects.get(pk=id)
        serializer = ProductSerializer(instance=product, many=False)
        return Response(serializer.data)

    def put(self, request, id):
        update = ProductModel.objects.get(pk=id)
        serializer = ProductSerializer(instance=update, data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors)
        else:
            serializer.save()
            return Response(serializer.data)

    def delete(self, request, id):
        product = ProductModel.objects.get(pk=id)
        product.delete()
        return Response(status=204)


from rest_framework.generics import ListCreateAPIView, RetrieveAPIView


class ProductListAPIView(ListCreateAPIView):
    queryset = ProductModel.objects.all()
    serializer_class = ProductSerializer


class ProductDetailListAPIView(RetrieveAPIView):
    queryset = ProductModel.objects.all()
    serializer_class = ProductSerializer


from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import OrderingFilter
from .filters import ProductFilter


class ProductViewSet(ModelViewSet):
    queryset = ProductModel.objects.all()
    serializer_class = ProductSerializer
    filter_class = ProductFilter  # 过滤
    filter_backends = [OrderingFilter]  # 排序
    ordering_fields = ('id', 'create_datetime', 'update_datetime', 'platform_code')  # 参与排序的字段
    pagination_class = LargeResultsSetPagination  # 分页
